<template>
  <div class="udp-uart-config-container">
    <!-- <el-card> -->
    <div slot="header" class="uart-config-header">
      串口转UDP配置
      <el-button type="primary" icon="el-icon-plus" size="mini" class="header-button" @click="adduartConfigRow"></el-button>
    </div>
    <el-row :gutter="20">
      <!-- Left Side: uart to UDP Configuration -->
      <el-col :span="24">
        <el-form ref="uartForm" :model="uartConfig" :rules="uartRules" size="mini" label-width="150px">
          <div class="table-container">
            <el-table :data="uartConfig.uart2udpRule" :height="tableHeight" border size="mini" fit>
              <el-table-column type="index" label="序号" width="80px" align="center"></el-table-column>
              <el-table-column label="串口输入">
                <template slot-scope="scope">
                  <el-form-item :prop="'uart2udpRule.' + scope.$index + '.uartId'" :rules="uartRules.uartId" label-width="0">
                    <el-select v-model="scope.row.uartId" placeholder="请选择串口">
                      <el-option v-for="(port, index) in uartPorts" :key="index" :label="port.label" :value="port.value"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="转发使能" width="120px" align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="'uart2udpRule.' + scope.$index + '.enable'" :rules="uartRules.enable" label-width="0">
                    <el-checkbox v-model="scope.row.enable" :true-label="1" :false-label="0"></el-checkbox>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="本端发送端口">
                <template slot-scope="scope">
                  <el-form-item :prop="'uart2udpRule.' + scope.$index + '.udpPort'" :rules="uartRules.udpPort" label-width="0">
                    <el-input v-model.number="scope.row.udpPort" clearable @clear="clearudpPort(scope.$index)"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="远端接收IP地址">
                <template slot-scope="scope">
                  <el-form-item :prop="'uart2udpRule.' + scope.$index + '.destIp'" :rules="uartRules.destIp" label-width="0">
                    <el-input v-model="scope.row.destIp" clearable @clear="cleardestIp(scope.$index)"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="远端接收端口">
                <template slot-scope="scope">
                  <el-form-item :prop="'uart2udpRule.' + scope.$index + '.destPort'" :rules="uartRules.destPort" label-width="0">
                    <el-input v-model.number="scope.row.destPort" clearable @clear="cleardestPort(scope.$index)"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="140px" align="center">
                <template v-if="scope.$index > 15" slot-scope="scope">
                  <el-button type="danger" size="mini" @click="removeConfigRow(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </el-col>
    </el-row>
    <!-- </el-card> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    var validatePort = (rule, value, callback) => {
      const portPattern = /^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/
      if (value === undefined || value === null || value.toString().trim() === '') {
        callback(new Error('端口不能为空'))
      } else if (portPattern.test(value)) {
        callback()
      } else {
        callback(new Error('端口号范围应在0到65535之间'))
      }
    }

    var validateIpAddress = (rule, value, callback) => {
      const ipRegex = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/
      if (value === undefined || value === null || value.toString().trim() === '') {
        callback(new Error('IP地址不能为空'))
      } else if (ipRegex.test(value)) {
        callback()
      } else {
        callback(new Error('无效的IP地址'))
      }
    }

    return {
      // uartConfig: {
      //   uart2udpRule: []
      // },
      uartPorts: Array.from({ length: 16 }, (_, i) => ({
        label: `串口-S${i + 1}`,
        value: i + 1
      })),
      tableHeight: 'calc(100vh - 270px)',
      uartRules: {
        uartId: [
          { required: true, message: '请选择串口', trigger: 'change' }
        ],
        enable: [
          { required: true, message: '请选择转发状态', trigger: 'change' }
        ],
        udpPort: [
          { required: true, message: '请输入本端发送端口', trigger: 'blur' },
          { validator: validatePort, trigger: 'blur' }
        ],
        destIp: [
          { required: true, message: '请输入远端接收IP地址', trigger: 'blur' },
          { validator: validateIpAddress, trigger: 'blur' }
        ],
        destPort: [
          { required: true, message: '请输入远端接收端口', trigger: 'blur' },
          { validator: validatePort, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['SysCfgInfo']),
    uartConfig() {
      return this.SysCfgInfo
    }
  },
  created() {
    // this.getSysCfg()
  },
  beforeDestroy() {
  },
  methods: {
    adduartConfigRow() {
      this.uartConfig.uart2udpRule.push({
        uartId: 1,
        enable: true,
        udpPort: null,
        destIp: '',
        destPort: null
      })
      this.$nextTick(() => this.$refs.uartForm.clearValidate())
    },
    removeConfigRow(index) {
      this.uartConfig.uart2udpRule.splice(index, 1)
      this.$nextTick(() => this.$refs.uartForm.clearValidate())
    },
    clearudpPort(index) {
      this.$refs.uartForm.validateField('uart2udpRule.' + index + '.udpPort')
    },
    cleardestIp(index) {
      this.$refs.uartForm.validateField('uart2udpRule.' + index + '.destIp')
    },
    cleardestPort(index) {
      this.$refs.uartForm.validateField('uart2udpRule.' + index + '.destPort')
    },
    save() {
      return new Promise((resolve, reject) => {
      // Implement the logic to save the HDLC-NRZ configuration
        this.$refs.uartForm.validate((valid) => {
          if (valid) {
            resolve(true)
          } else {
            this.$message.warning('串口转以太网标签表单校验失败')
            resolve(false)
          }
        })
      })
    },
    getSettings() {
      this.$nextTick(() => this.$refs.uartForm.clearValidate())
    },
    getSysCfg(flag = 0) {
      this.loading = true
      this.$store.dispatch('device/getSysCfg').then(res => {
        this.loading = false
        this.uartConfig.uart2udpRule = res.uart2udpRule
        this.$nextTick(() => this.$refs.uartForm.clearValidate())
        if (flag === 1) {
          this.$message.success('串口转以太网信息获取成功')
        }
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.udp-uart-config-container {
  .table-container {
    overflow: auto;
  }

  .header-button {
    float: right;
  }

  .uart-config-header {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
  }

}
</style>
